package cn.bincker.audiostream;

import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

@ServerEndpoint("/audio")
@Component
public class AudioEndpointExporter {
    @OnMessage
    public void onMessage(String message, Session session){
        if("play".equals(message)){
            try(InputStream in = new FileInputStream(ResourceUtils.getFile("classpath:static/music1.mp3"))) {
                byte[] bytes = new byte[8192];
                int len;
                while ((len = in.read(bytes)) > 0) {
                    session.getBasicRemote().sendBinary(ByteBuffer.wrap(bytes, 0, len));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
